<template>
	<div style="height:100%">
		<!-- 主要内容 -->
		<div class="loginWrapper">
			<div class="container loginInline">
				<div class="loginContent">
					<router-link to="/index">
						<h1 class="hidden-md-and-up phoneTitle">数据资产运营平台</h1>
					</router-link>
					<div class="inlinContent">
						<el-row style="display: flex;align-items: center;">
							<el-col class="hidden-xs-only hidden-sm-only" :xs="8" :sm="6" :md="12" :lg="14" :xl="14">
								<div class="loginLeft">
									<div class="leftInline">
										<router-link to="/index">
											<img src="@/assets/img/logo.png" alt="">
											<div class="loginoText">
												<h1>数据资产运营平台</h1>
												<h4>Data Asset Operation Platform</h4>
											</div>
										</router-link>
									</div>
								</div>
							</el-col>
							<el-col :xs="24" :sm="24" :md="12" :lg="10" :xl="10">
								<div class="loginRight">
									<!-- 账号密码登录 -->
									<h2 class="loginBig">用户登录</h2>
									<el-form :model="accountForm" :rules="accountRule" ref="accountForm"
										class="demo-ruleForm">
										<el-form-item prop="userName">
											<el-input v-model="accountForm.userName" placeholder="请输入用户账号"></el-input>
										</el-form-item>
										<el-form-item prop="password">
											<el-input v-model="accountForm.password" placeholder="请输入密码" show-password>
											</el-input>
										</el-form-item>
										<el-form-item prop="code">
											<el-col :span="16">
												<el-input v-model="accountForm.code" placeholder="请输入验证码"></el-input>
											</el-col>
											<el-col :span="5">
												<img class="imgCode" width="100" :src="codeImg" @click="updateCode"
													alt="">
											</el-col>
										</el-form-item>
									</el-form>
									<!-- 协议 -->
									<!-- <div class="agreementOne">
										<el-tooltip v-model="visible" class="item" effect="dark" content="请阅读并勾选协议"
											placement="top-start">
											<el-checkbox v-model="checkedAgree" @change="checkboxchange">
											</el-checkbox>
										</el-tooltip>
										<span class="agreement">我已经认真阅读、理解并同意<a target="_blank"
												href="/privacy">《隐私政策》</a><a target="_blank"
												href="/service">《用户服务协议》</a></span>
									</div> -->
									<!-- 提交 -->
									<div>
										<el-button :loading="loading" @click="accountBtn()" class="submitBtn"
											type="primary">登录</el-button>
									</div>
									<!-- <div class="loginReg">
										<a class="forgetBtn" href="/forgetPwdEmail">忘记密码</a>
										<a class="regBtn" href="/register">注册账户</a>
									</div> -->

								</div>

							</el-col>
						</el-row>
					</div>

				</div>
			</div>
			<SimpleFooter />
		</div>
	</div>
</template>
<script>
	import {
		getCodeImg,
		login,
		sendEmail,
		emailLogin,
		phoneLogin,
		sendPhone,
	} from "@/request/api/login";
	import {
		getUserInfo2
	} from "@/request/api/user";
	import SimpleFooter from "@/components/home/simpleFooter/simpleFooter";
	import {
		aesEncrypt
	} from "@/utils/crypto.js";
	export default {
		components: {
			SimpleFooter,
		},
		data() {
			var checkPhone = (rule, value, callback) => {
				if (!value) {
					return callback(new Error("手机号不能为空"));
				}
				if (!Number.isInteger(value)) {
					callback(new Error("请输入数字值"));
				} else {
					if (/^1(3|4|5|7|8)\d{9}$/.test(value) == false) {
						callback(new Error("请输入有效的手机号"));
					} else {
						callback();
					}
				}
			};
			var checkEmail = (rule, value, callback) => {
				if (!value) {
					return callback(new Error("请输入邮箱"));
				}
				if (
					/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/.test(value) ==
					false
				) {
					callback(new Error("请输入有效的邮箱"));
				} else {
					callback();
				}
			};
			return {
				loading: false,
				activeName: "account",
				accountForm: {
					enterpriseName: "syxfpt", //企业账号
					userName: "", //用户账号
					password: "", //用户密码
					code: "", //验证码
					uuid: "", //验证码获取的
				},
				emailForm: {
					email: "", //邮箱
					code: "", //验证码
				},
				phoneForm: {
					enterpriseName: "jngxzhyq",
					phone: "", //账号绑定的手机号   目前账号-思创
					phoneCode: "",
				},
				codeImg: "",
				accountRule: {
					enterpriseName: [{
						required: true,
						message: "请输入企业账号",
						trigger: "blur"
					}, ],
					userName: [{
						required: true,
						message: "请输入用户账号",
						trigger: "blur"
					}, ],
					password: [{
						required: true,
						message: "请输入用户密码",
						trigger: "blur"
					}, ],
					code: [{
						required: true,
						message: "请输入验证码",
						trigger: "blur"
					}],
				},
				phoneRule: {
					phone: [{
						required: true,
						message: "请输入手机号",
						trigger: "blur"
					}, ],
					phoneCode: [{
						required: true,
						message: "请输入手机验证码",
						trigger: "blur"
					}, ],
				},
				emailRule: {
					email: [{
						required: true,
						validator: checkEmail,
						trigger: "blur"
					}],
					code: [{
						required: true,
						message: "请输入邮箱验证码",
						trigger: "blur"
					}, ],
				},
				checkedAgree: true,
				visible: false,
				ws: null,
				leave_page: false,
				is_first_in_page: true, // 判断是否是第一次进入页面，在 websocket 连接成功时判断是否调用子路由
				token: "",
				btnTxt: "获取验证码",
				disabled: false,
				time: 60,
				routeUrl: this.$route.query.redirect, //重定向页面
				path: this.$route.query.path,
				id: this.$route.query.id,
				btnTxt2: "获取验证码",
				disabled2: false,
				time2: 60,
				// height: 827
			};
		},
		mounted() {
			this.updateCode();
			// this.$nextTick(() => {
			//   // 动态给背景图片设置高度
			//   var hh = document.documentElement.clientHeight;//这个是窗口的高度
			//   let offsetHeight = document.getElementById("logoHeader").offsetHeight;//这部分比如说是页面中其他div的高度，请视自己情况而定
			//   this.height = hh - offsetHeight//需要设置的dom元素  进行高度设置 
			// })
		},
		watch: {

		},
		methods: {
			handleClick() {},
			// 获取验证码
			updateCode() {
				// this.codeImg =
				// 	process.env.VUE_APP_SERVICE_URL + "/portal/user/createCode?" + Math.random();
				getCodeImg({
					// t: Math.random(),
				}).then((res) => {
					// console.log('验证码', res.data);
					// if (res.data.code === 200) {
					  // this.codeImg = "data:image/png;base64," + this.arrayBufferToBase64(res.data);
					  // console.log('验证码', this.codeImg);
					//   this.accountForm.uuid = res.data.result.uuid;
					// }
					
					// const binaryData = res.data; // 替换为真正的二进制数据
					// // 创建Blob对象
					// const blob = new Blob([binaryData], {
					// 	type: 'application/octet-stream'
					// });
					// // 创建URL对象
					// const urlCreator = window.URL || window.webkitURL;
					// const imgUrl = urlCreator.createObjectURL(blob);
					// // 将URL赋值给data属性
					// this.codeImg = imgUrl;
					// console.log('验证码', this.codeImg);

					let info = res.data;
					let blob = new Blob([info]);
					this.codeImg = URL.createObjectURL(blob);
					// console.log('验证码',this.codeImg);
				});
			},
			arrayBufferToBase64(buffer) {
				var binary = ""
				var bytes = new Uint8Array(buffer)
				var len = bytes.bytelength
				for (var i = 0; i < len; i++) {
					binary += String.fromCharCode(bytes[i])
				}
				return window.btoa(binary)
			},
			md5(str) {
				const CryptoJS = require('crypto')
				const hash = CryptoJS.createHash('md5')
				hash.update(str)
				return hash.digest('hex')
			},
			sha256(str) {
				const CryptoJS = require('crypto')
				const hash = CryptoJS.createHash('sha256')
				hash.update(str)
				return hash.digest('hex')
			},
			// 账号密码登录
			accountBtn() {
				if (this.activeName === "account") {
					//账号登录
					this.$refs.accountForm.validate((valid) => {
						if (valid) {
							if (this.checkedAgree == false) {
								this.visible = true;
								return;
							}
							let params = {
								userName: this.accountForm.userName,
								passWord: this.sha256(this.md5(this.accountForm.password)),
								code: this.accountForm.code
							}
							this.loading = true
							login(params).then((res) => {
								this.loading = false
								if (res.data.code == 1) {
									this.$message({
										message: res.data.message,
										type: "success",
									});

									window.sessionStorage.setItem(
										"userInfo",
										JSON.stringify(res.data.data)
									);
									this.token = res.data.data.token;
									// console.log('this.token',this.token)
									window.sessionStorage.setItem(
										"access_token",
										res.data.data.token
									);
									setTimeout(() => {
										this.$router.push("/index");
									}, 1000);


									// getUserInfo2().then((res) => {
									// 	if (res.data.code === 200) {
									// 		var userInfo = res.data.result;
									// 		//请求回来后，把用户信息存储到VUEX里
									// 		this.$store.dispatch('user/alreadyInfo', res.data
									// 			.result)
									// 		// 存储信息
									// 		window.sessionStorage.setItem(
									// 			"userInfo",
									// 			JSON.stringify(userInfo)
									// 		);
									// 	}
									// });
									// setTimeout(() => {
									// 	if (this.$route.query.redirect) {
									// 		this.$router.push(this.routeUrl);
									// 	} else if (this.$route.query.path) {
									// 		this.$router.push({
									// 			name: this.path,
									// 			query: {
									// 				id: this.id,
									// 			},
									// 		});
									// 	} else {
									// 		this.$router.push("/msgCenterNone");
									// 	}
									// 	this.bus.$emit("connectWeb");
									// }, 1000);
								} else {
									// this.updateCode();
									this.$message.error(res.data.message);
								}
							});
						}
					});
				} else if (this.activeName === "email") {
					//邮箱登录
					this.$refs.emailForm.validate((valid) => {
						if (valid) {
							if (this.checkedAgree == false) {
								this.visible = true;
								return;
							}
							emailLogin(this.emailForm).then((res) => {
								if (res.data.code == 200) {
									this.emailForm.email = '',
										this.emailForm.code = '',
										this.$message({
											message: res.data.message,
											type: "success",
										});
									this.token = res.data.result.access_token;
									window.sessionStorage.setItem(
										"access_token",
										res.data.result.access_token
									);
									getUserInfo2().then((res) => {
										if (res.data.code === 200) {
											var userInfo = res.data.result;
											//请求回来后，把用户信息存储到VUEX里
											this.$store.dispatch('user/alreadyInfo', res.data
												.result)
											// 存储信息
											window.sessionStorage.setItem(
												"userInfo",
												JSON.stringify(userInfo)
											);
										}
									});
									setTimeout(() => {
										if (this.$route.query.redirect) {
											this.$router.push(this.routeUrl);
										} else if (this.$route.query.path) {
											this.$router.push({
												name: this.path,
												query: {
													id: this.id,
												},
											});
										} else {
											this.$router.push("/msgCenterNone");
										}
										this.bus.$emit("connectWeb");
									}, 1000);
									// setTimeout(() => {
									//   // this.$router.push("/index");
									//   this.$router.push("/msgCenterNone");
									//   this.bus.$emit("connectWeb");
									// }, 1000);
								} else {
									this.updateCode();
									this.$message.error(res.data.message);
								}
							});
						}
					});
				} else if (this.activeName === "phone") {
					//手机号登录
					this.$refs.phoneForm.validate((valid) => {
						if (valid) {
							let params = JSON.parse(JSON.stringify(this.phoneForm));
							phoneLogin(params).then((res) => {
								if (res.data.code == 200) {
									// console.log(params);
									this.phoneForm.phone = '',
										this.phoneForm.phoneCode = '',
										this.$message({
											message: res.data.message,
											type: "success",
										});
									this.token = res.data.result.access_token;
									window.sessionStorage.setItem(
										"access_token",
										res.data.result.access_token
									);
									getUserInfo2().then((res) => {
										if (res.data.code === 200) {
											var userInfo = res.data.result;
											// 存储信息
											window.sessionStorage.setItem(
												"userInfo",
												JSON.stringify(userInfo)
											);
										}
									});
									setTimeout(() => {
										if (this.$route.query.redirect) {
											this.$router.push(this.routeUrl);
										} else if (this.$route.query.path) {
											this.$router.push({
												name: this.path,
												query: {
													id: this.id,
												},
											});
										} else {
											this.$router.push("/msgCenterNone");
										}
										this.bus.$emit("connectWeb");
									}, 1000);
								} else {
									this.updateCode();
									this.$message.error(res.data.message);
								}
							});
						} else {
							return false;
						}
					});
				}
			},
			// 点击获取验证码-邮箱
			logInCode() {
				if (this.emailForm.email === "") {
					this.$message({
						message: "请输入邮箱！ ",
						type: "warning",
					});
					return false;
				}
				this.getSendEmail(this.emailForm.email);
			},
			// 点击获取验证码-手机号
			logInCode2() {
				if (this.phoneForm.phone === "") {
					this.$message({
						message: "请输入手机号！ ",
						type: "warning",
					});
					return false;
				}
				this.getSendPhone(this.phoneForm.phone);
			},
			// 发送手机验证码-邮箱
			getSendEmail(email) {
				let params = {
					email,
				};
				sendEmail(params).then((res) => {
					if (res.data.code === 200) {
						this.$notify({
							title: "成功",
							message: res.data.message,
							type: "success",
						});
						this.time = 60;
						this.timer();
					} else {
						this.$notify({
							title: "错误",
							message: res.data.message,
							type: "error",
						});
					}
				});
			},
			//发送手机验证码倒计时-邮箱
			timer() {
				if (this.time > 0) {
					this.disabled = true;
					this.time--;
					this.btnTxt = this.time + "秒";
					setTimeout(this.timer, 1000);
				} else {
					this.time = 0;
					this.btnTxt = "获取验证码";
					this.disabled = false;
				}
			},
			//发送手机验证码倒计时-手机号
			timer2() {
				if (this.time2 > 0) {
					this.disabled2 = true;
					this.time2--;
					this.btnTxt2 = this.time2 + "秒";
					setTimeout(this.timer2, 1000);
				} else {
					this.time2 = 0;
					this.btnTxt2 = "获取验证码";
					this.disabled2 = false;
				}
			},
			// 发送手机验证码-手机号
			getSendPhone(phone) {
				let params = {
					phone,
				};
				sendPhone(params).then((res) => {
					if (res.data.code === 200) {
						this.$notify({
							title: "成功",
							message: res.data.message,
							type: "success",
						});
						this.time2 = 60;
						this.timer2();
					} else {
						this.$notify({
							title: "错误",
							message: res.data.message,
							type: "error",
						});
					}
				});
			},
			checkboxchange(val) {
				this.visible = false;
			},
		},
	};
</script>
<style lang="less" scoped>
	@import "./login.less";
	@import "./media.less";
</style>